/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.cef.repository.typetransprocesser;

import com.inspur.edp.cef.api.repository.ITypeTransProcesser;
import com.inspur.edp.cef.entity.condition.FilterCondition;
import com.inspur.edp.cef.repository.exception.CefRepositoryException;
import com.inspur.edp.cef.repository.utils.FilterUtil;
import com.inspur.edp.cef.spi.entity.info.EnumValueInfo;
import com.inspur.edp.cef.spi.entity.info.propertyinfo.EnumPropertyInfo;

import java.sql.Connection;

public class Enum2VarcharProcesser implements ITypeTransProcesser
{
	private static Enum2VarcharProcesser instance;
	private EnumPropertyInfo enumPropertyInfo;

	public static Enum2VarcharProcesser getInstacne()
	{
		if (instance == null)
		{
			instance = new Enum2VarcharProcesser();
		}
		return instance;
	}

	public static Enum2VarcharProcesser getInstance( EnumPropertyInfo enumPropertyInfo)
	{
		return new Enum2VarcharProcesser(enumPropertyInfo);
	}


	private Enum2VarcharProcesser()
	{

	}

	private Enum2VarcharProcesser(EnumPropertyInfo enumPropertyInfo)
	{
		this.enumPropertyInfo = enumPropertyInfo;
	}

	public final Object transType(FilterCondition filter, Connection db)
	{
		filter.setValue((String) transType(filter.getValue().toString()));
		return FilterUtil.processStringValue(filter);
	}

	public final Object transType(Object value)
	{
		if (value == null)
		{
			return null;
		}
		try
		{
		    if(enumPropertyInfo==null) {
                if (value.getClass().isEnum()) {
                    return new Enum2IntProcesser(value.getClass()).transType(value).toString();
                }
                int result = (Integer) value;
                return (new Integer(result)).toString();
            }
            EnumValueInfo enumValueInfo= enumPropertyInfo.getEnumValueInfo(value.toString());
		    if(enumValueInfo==null)
			 enumValueInfo=enumPropertyInfo.getStringIndexEnumValueInfo(value.toString());
		    if(enumValueInfo==null)
			{
				throw new CefRepositoryException("转换字段格式时出错，找不到枚举值【"+value.toString()+"】");
			}
		    return enumValueInfo.getStringIndex();
		}
		catch (RuntimeException e)
		{
			throw new CefRepositoryException("ErrorType", e);
		}
	}

	@Override
	public Object transType(Object value, boolean isNull) {
		return transType(value);
	}
}
